// initialize default value
function getTheme(){
    return localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
}

function setTheme(style){
    document.documentElement.setAttribute('data-theme', style);
    localStorage.setItem('theme', style);  
}

function showToc() {
    $('.post-toc').toggleClass('post-toc-show');
    $('.single-post').toggleClass('single-post-toc');
}

function backTop() {
    $("body,html").animate({scrollTop:0},500);
}

function tocScroll() {
    var target = decodeURI(this.hash.replace(/^#/, ''));
    $("body,html").animate({scrollTop: $(":header[id='" + target + "']").offset().top - 40}, 300);
}

function showSearch() {
    $('.search').addClass('search-show');
    $('.cover').addClass('cover-show');
}

function hideSearch() {
    $('.search').removeClass('search-show');
    $('.cover').removeClass('cover-show');
}

function getReadPercentage() {
    window.onscroll=function() {
        var wintop = $(window).scrollTop();
        var docheight = $(document).height();
        var winheight = $(window).height();
        var scrolled = Math.round((wintop / (docheight - winheight)) * 100);
        $('#read-percentage').html(scrolled+'%');
    }
}

// function tocSlide() {
//     $(".toc-h4").hide();
//     $(".toc-h5").hide();
//     var h3HasChild = $(".toc-h3 li:has(+ .toc-h4)");
//     var h4HasChild = $(".toc-h4 li:has(+ .toc-h5)");
//     h4HasChild.prepend("<span class='toc-icon'>></span>");
//     h3HasChild.prepend("<span class='toc-icon'>></span>");
//     h3HasChild.on('click',function(){
//         $(this).next(".toc-h4").slideToggle();
//     });
//     h4HasChild.on('click',function(){
//         $(this).next(".toc-h5").slideToggle();
//     });
// }

function flashCopyMessage(el, msg) {
    el.textContent = msg;
    setTimeout(function() {
      el.textContent = "Copy";
    }, 1000);
}

function selectText(node) {
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(node);
    selection.removeAllRanges();
    selection.addRange(range);
    return selection;
}

function addCopyButton(containerEl) {
    var copyBtn = document.createElement("button");
    copyBtn.className = "highlight-copy-btn";
    copyBtn.textContent = "Copy";

    var codeEl = containerEl.firstElementChild.firstElementChild.firstElementChild.firstElementChild.children[1];
    copyBtn.addEventListener('click', function() {
      try {
        var selection = selectText(codeEl);
        document.execCommand('copy');
        selection.removeAllRanges();
        flashCopyMessage(copyBtn, 'Copied!')
      } catch(e) {
        console && console.log(e);
        flashCopyMessage(copyBtn, 'Failed :\'(')
      }
    });
    containerEl.appendChild(copyBtn);
}

function switchTheme(e) {
    var theme = getTheme();
    if (theme == 'light') {
        setTheme('dark');
    }
    else {
        setTheme('light');
    }
}

function init(){
    var theme = getTheme();
    const userPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    if (theme === null) {
        if(userPrefersDark){
            setTheme('dark');
        }
        else{
            setTheme('light');
        }
    }
    else {
        if (theme == 'light') {
            document.documentElement.setAttribute('data-theme', 'light');
        }
        else {
            document.documentElement.setAttribute('data-theme', 'dark');
        }    
    }    
}

init();

document.addEventListener('DOMContentLoaded', function() {
    var searchBtn = document.querySelector('#search-btn');
    searchBtn.addEventListener('click', showSearch, false);
    var cover = document.querySelector('.cover');
    cover.addEventListener('click', hideSearch, false);
    if(document.querySelector('.post-menu')!=null){
        var backTopBtn = document.querySelector('#back-top-btn');
        backTopBtn.addEventListener('click', backTop, false);
        var themeSwitcher = document.querySelector('#switch-btn');
        themeSwitcher.addEventListener('click', switchTheme, false);
    }
    if(document.querySelector('.post-toc')!=null){
        getReadPercentage();
        var tocLinks = document.querySelectorAll('.toc-link');
        for( var i in tocLinks){
            tocLinks[i].onclick = tocScroll;
        };
        // tocSlide();
        var tocBtn = document.querySelector('#toc-btn');
        tocBtn.addEventListener('click', showToc, false);
    }
    var highlightBlocks = document.getElementsByClassName('highlight');
    if(highlightBlocks!=null){
        Array.prototype.forEach.call(highlightBlocks, addCopyButton);
    }
}, false);

